package liuliu.throughwaring.ui.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.CodeNote;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.custom.model.CodeModel;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.PersonModel;
import liuliu.throughwaring.model.PoliceModel;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 民警信息管理页面
 * 作者：柳伟杰 on 2016/3/23 16:15
 * 邮箱：1031066280@qq.com
 */
public class PoliceAndLiuDongActivity extends BaseActivity {
    public static PoliceAndLiuDongActivity mInstance;
    @CodeNote(id = R.id.police_toolbar)
    TToolbar police_toolbar;
    @CodeNote(id = R.id.no_data_ll)
    LinearLayout no_data_ll;
    @CodeNote(id = R.id.police_lv)
    ListView police_lv;
    @CodeNote(id = R.id.cha_btn, click = "onClick")
    Button cha_btn;
    @CodeNote(id = R.id.add_btn, click = "onClick")
    Button add_btn;
    CommonAdapter<PoliceModel> police_mAdapter;
    CommonAdapter<PersonModel> person_mAdapter;
    String style = "";
    String key_val = "";
    PopupWindow bottom_pop;
    @CodeNote(id = R.id.total_num_tv)
    TextView total_num_tv;
    @CodeNote(id = R.id.police_yue, click = "onClick")
    TextView yue;
    @CodeNote(id = R.id.police_nian, click = "onClick")
    TextView nian;
    @CodeNote(id = R.id.police_ri, click = "onClick")
    TextView ri;
    @CodeNote(id = R.id.liudong_select_type)
    LinearLayout liudongType;
    String startTime = "";
    String endTime = "";
    int selectTitle = 1;

    @Override
    public void initViews() {
        setContentView(R.layout.activity_police);
        mInstance = this;
        style = getIntent().getStringExtra("style");
        police_toolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                mInstance.finish();
            }
        });
        getTime(1);
    }

    @Override
    public void initEvents() {
        switch (style) {
            case "liudong":
                police_toolbar.setLeftTitle("盘查人员");
                liudongType.setVisibility(View.VISIBLE);
                break;
            case "police":
                police_toolbar.setLeftTitle("民警管理");
                cha_btn.setText("民警查询");
                add_btn.setText("民警添加");
                liudongType.setVisibility(View.GONE);
                break;
        }
        getTime(1);
    }

    boolean nodata = false;

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cha_btn:
                showPopWindow(cha_btn);
                break;
            case R.id.add_btn://添加按钮点击事件
                Intent intent;
                Bundle bundle;
                switch (style) {
                    case "liudong":
                        intent = new Intent();
                        intent.setClass(PoliceAndLiuDongActivity.this, RegPersonActivity.class);
                        intent.putExtra("CompanyId", "1306010015");
                        startActivityForResult(intent, 0);
                        break;
                    case "police":
                        intent = new Intent();
                        intent.setClass(PoliceAndLiuDongActivity.this, RegPoliceActivity.class);
                        startActivityForResult(intent, 0);
                        break;
                }
                break;
            case R.id.police_ri:
                //改变样式
                ri.setTextColor(getResources().getColor(R.color.white));
                yue.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
                nian.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
                nian.setBackgroundColor(getResources().getColor(R.color.white));
                yue.setBackgroundColor(getResources().getColor(R.color.white));
                ri.setBackgroundResource(R.mipmap.select_background);
                getTime(1);
                break;
            case R.id.police_yue:
                getTime(2);
                ri.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
                yue.setTextColor(getResources().getColor(R.color.white));
                nian.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
                nian.setBackgroundColor(getResources().getColor(R.color.white));
                ri.setBackgroundColor(getResources().getColor(R.color.white));
                yue.setBackgroundResource(R.mipmap.select_background);
                break;
            case R.id.police_nian:
                getTime(3);
                nian.setTextColor(getResources().getColor(R.color.white));
                yue.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
                ri.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
                ri.setBackgroundColor(getResources().getColor(R.color.white));
                yue.setBackgroundColor(getResources().getColor(R.color.white));
                nian.setBackgroundResource(R.mipmap.select_background);

                break;
        }
    }

    private void getTime(int type) {
        selectTitle = type;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR); //获取当前年份
        int mMonth = c.get(Calendar.MONTH) + 1;//获取当前月份
        int mDay = c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = format.format(ca.getTime());
        String maxMonth = last.substring(8, 10);
        //System.out.println("==========" + maxMonth);

        String nianLast = format.format(getYearLast(mYear));
        //System.out.println("==========" + nianLast);

        String nianFirst = format.format(getYearFirst(mYear));
        System.out.println("==========" + nianFirst);
        //当天
        if (type == 1) {
            startTime = mYear + "";
            if (mMonth < 10) {
                startTime = startTime + "-0" + mMonth;
            } else {
                startTime = startTime + "-" + mMonth;
            }
            if (mDay < 10) {
                startTime = startTime + "-0" + mDay;
            } else {
                startTime = startTime + "-" + mDay;
            }
            endTime = startTime;
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
        } else if (type == 2) {
            //当月
            startTime = mYear + "";
            if (mMonth < 10) {
                startTime = startTime + "-0" + mMonth;
            } else {
                startTime = startTime + "-" + mMonth;
            }
            endTime = startTime;
            startTime = startTime + "-01 00:00:00";
            endTime = endTime + "-" + maxMonth + " 23:59:59";
        } else if (type == 3) {
            //当年
            startTime = nianFirst + " 00:00:00";
            endTime = nianLast + " 23:59:59";
        }
        loadPolice();
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }

    /**
     * 根据条件查询警员或流动人员信息
     */
    private void loadPolice() {
        String slq = "PersonName like '%" + key_val
                + "%' and PersonComapnyType='Free'and  PersonCreateTime BETWEEN '" + startTime + "' and  '" + endTime + "' order by PersonCreateTime desc";
        switch (style) {
            case "liudong":
                final List<PersonModel> liudong = finalDb.findAllByWhere(PersonModel.class, slq);
                if (liudong != null) {
                    total_num_tv.setText("人员数量：" + liudong.size() + "人");
                    if (liudong.size() > 0) {
                        nodata = true;
                        person_mAdapter = new CommonAdapter<PersonModel>(mInstance, liudong, R.layout.item_liudong) {
                            @Override
                            public void convert(ViewHolder holder, final PersonModel person, int position) {
                                holder.setPersonImageUrl(R.id.touxiang_iv, person.getPersonImgUrl());
                                holder.setText(R.id.xuhao_tv, (position + 1) + "");
                                holder.setText(R.id.user_name_tv_liudong, person.getPersonName());
                                holder.setText(R.id.create_time_tv_liudong, Utils.loadTime(person.getPersonCreateTime()));
                                holder.setText(R.id.user_unit_tv_liudong, Utils.cutStringWithDian(Utils.setDefault(person.getPersonAddress(), "无"), 24));
                                holder.setText(R.id.user_unit_tv_guanlian, getGuanLianNum(person.getPersonCardId()) + "");

                                holder.setOnClickListener(R.id.detail_btn, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //跳转到详细页面
                                        mUtils.IntentPost(PersonDetailActivity.class, new Utils.putListener() {
                                            @Override
                                            public void put(Intent intent) {
                                                intent.putExtra("personid", person.getPersonId());
                                            }
                                        });
                                    }
                                });
                                if (("2").equals(person.getPersonSex())) {
                                    holder.setText(R.id.sex_tv, "女");
                                }
                                holder.setText(R.id.nation_tv, getNativeName(person.getPersonNation()));
                            }
                        };
                        police_lv.setAdapter(person_mAdapter);
                        police_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                                //跳转到详细页面
                                mUtils.IntentPost(PersonDetailActivity.class, new Utils.putListener() {
                                    @Override
                                    public void put(Intent intent) {
                                        intent.putExtra("personid", liudong.get(position).getPersonId());
                                    }
                                });
                            }
                        });
                        police_lv.setVisibility(View.VISIBLE);
                        no_data_ll.setVisibility(View.GONE);
                    } else {
                        police_lv.setVisibility(View.GONE);
                        no_data_ll.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case "police":
                final List<PoliceModel> polices = finalDb.findAllByWhere(PoliceModel.class, "(PoliceName like '%" + key_val + "%' or PoliceId like '%" + key_val + "%' ) order by PoliceCreateTime desc");
                if (polices != null) {
                    total_num_tv.setText("人员数量：" + polices.size() + "人");
                    if (polices.size() > 0) {
                        nodata = true;
                        police_mAdapter = new CommonAdapter<PoliceModel>(mInstance, polices, R.layout.item_police) {
                            @Override
                            public void convert(ViewHolder holder, final PoliceModel policeModel, int position) {
                                holder.setPoliceImageUrl(R.id.touxiang_iv, policeModel.getPoliceCardImage());
                                holder.setText(R.id.xuhao_tv, (position + 1) + "");
                                holder.setText(R.id.police_name_tv, policeModel.getPoliceName());
                                holder.setText(R.id.police_tel_tv, policeModel.getPolicePhoneNumber());
                                holder.setOnClickListener(R.id.call_ll, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + policeModel.getPolicePhoneNumber()));
                                        startActivity(intent);
                                    }
                                });
                                holder.setText(R.id.police_id_tv, policeModel.getPoliceId());
                            }
                        };
                        police_lv.setAdapter(police_mAdapter);
                        police_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                                mUtils.IntentPost(PoliceDetailActivity.class, new Utils.putListener() {
                                    @Override
                                    public void put(Intent intent) {
                                        intent.putExtra("policeId", polices.get(position).getPoliceId());
                                    }
                                });
                            }
                        });
                        police_lv.setVisibility(View.VISIBLE);
                        no_data_ll.setVisibility(View.GONE);
                    } else {
                        police_lv.setVisibility(View.GONE);
                        no_data_ll.setVisibility(View.VISIBLE);
                    }
                }
                break;
        }
    }

    private String getNativeName(String nativeid) {
        List<CodeModel> list = finalDb.findAllByWhere(CodeModel.class, "Name='" + nativeid + "'");
        if (list.size() > 0) {
            return list.get(0).getValue();
        }
        return "汉族";
    }

    //关联信息几条
    private int getGuanLianNum(String cardid) {
        //按企业分类
        List<PersonModel> list = finalDb.findAllByWhere(PersonModel.class, "PersonCardId='" + cardid + "'");
        List<CompanyModel> guList = new ArrayList<CompanyModel>();
        for (PersonModel p : list) {
            List<CompanyModel> clist = finalDb.findAllByWhere(CompanyModel.class, "CompanyId='" + p.getPersonCompanyId() + "'");
            if (clist.size() > 0) {
                Boolean isY = true;
                for (CompanyModel c : guList) {
                    if (c.getCompanyId().equals(clist.get(0).getCompanyId())) {
                        isY = false;
                        break;
                    }
                }
                if (isY) {
                    guList.add(clist.get(0));
                }
            }
        }
        return guList.size();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (resultCode == 133 || resultCode == 131) {
                key_val = "";
                getTime(1);
            }
        }
    }

    /**
     * 显示PopWindow
     *
     * @param v 点击的组件
     */
    private void showPopWindow(View v) {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.pop_search_word, null);
        final EditText danwei_et = (EditText) view.findViewById(R.id.danwei_name_et);
        final Button cha = (Button) view.findViewById(R.id.cha_btn);
        if (key_val.length() > 0) {
            danwei_et.setText(key_val);
            danwei_et.setSelection(key_val.length());
        }
        switch (style) {
            case "liudong":
                danwei_et.setHint("人员姓名");
                break;
            case "police":
                danwei_et.setHint("民警姓名、警员编号");
                break;
        }

        danwei_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!danwei_et.getText().toString().isEmpty()) {
                    cha.setText("查询");
                } else {
                    cha.setText("取消");
                }
            }
        });
        cha.setOnClickListener(new View.OnClickListener() {//天气信息被点击进行跳页
            @Override
            public void onClick(View v) {
                if (cha.getText().equals("查询")) {
                    key_val = danwei_et.getText().toString().trim();
                    police_toolbar.setLeftTitle("条件：" + key_val);
                    getTime(selectTitle);
                } else if (cha.getText().equals("取消")) {
                    key_val = "";
                    switch (style) {
                        case "liudong":
                            police_toolbar.setLeftTitle("盘查人员");
                            getTime(selectTitle);
                            break;
                        case "police":
                            police_toolbar.setLeftTitle("民警管理");
                            loadPolice();
                            break;
                    }
                }
                bottom_pop.dismiss();
            }
        });
        bottom_pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        bottom_pop.setAnimationStyle(R.style.pop_main_bottom_anim_style);
        bottom_pop.setFocusable(true);
        bottom_pop.setOutsideTouchable(true);
        bottom_pop.setBackgroundDrawable(new BitmapDrawable());
        bottom_pop.showAtLocation(v, Gravity.BOTTOM, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        bottom_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                bottom_pop.dismiss();
            }
        });
    }
}
